package com.bawei.broadcast2

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.localbroadcastmanager.content.LocalBroadcastManager

//本地广播
class MainActivity : AppCompatActivity() {
    private val receiver =LocalReceiver()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //动态注册本地广播
        val intentFilter = IntentFilter()
        intentFilter.addAction("com.bawei.wuxu")
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver,intentFilter)
    }
    //解除本地广播
    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
    }
    //发送广播，其他app能接收到
    fun send(view: View) {

        val intent = Intent("com.bawei.wuxu")
        sendBroadcast(intent)
    }
    //发送本地广播，只能本地能接受
    fun sendLoccal(view: View) {

        val intent = Intent("com.bawei.wuxu")
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }
    //广播接收器
    class LocalReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.d("ytx", "本地自己接收到: ")
        }

    }


}